import {getUserInfo, getUserAddress, getAccountList} from '@/api/user.js';
import {error, timeFormat} from '@/uni_modules/uv-ui-tools/libs/function/index.js';

const state = {
	userInfo: {
		memberMoney: {
			balance: 0,
			surplus: 0,
			integral: 0
		}
	},
	recordList: null,
	addressList: [],
	orderStatus: null,
	defaultAddress: null,
	selectAddress: null,
	selectAccount: null,
	accountList: [],
	defaultAccount: null
}

const actions = {
	//查询用户信息
	async getUserInfo({commit, state}) {
		await getUserInfo({id: uni.getStorageSync('memberId')}).then(res => {
			if (res.success) {
				res.data.expire = res.data.memberExtend.vipDate ? timeFormat(res.data.memberExtend.vipDate, 'yyyy年mm-dd') : '';
				commit('setUserInfo', res.data);
				return res;
			}
		}).catch(error => {
			console.log(error);
		})
	},
	//查询用户地址信息
	async getUserAddress({commit}, pload) {
		await getUserAddress({pageNumber: 1, pageSize: 100, memberId: uni.getStorageSync('memberId')}).then(res => {
			if (res.success) {
				const {data:{records}} = res;	
				commit('setAddressList', records);
				if (!records.length) {
					commit('setDefaultAddress', null);
				} else {
					const listTmp = records.filter(item => item.isdefault);
					if (listTmp.length) {
						commit('setDefaultAddress', listTmp[0]);
					} else if (records.length) {
						commit('setDefaultAddress', records[0]);
					}
				}
			}
			
		})
	},
	async getAccountList({commit}) {
		await getAccountList({pageNumber: 1, pageSize: 10, accountId: uni.getStorageSync('memberId')}).then(res => {
			if (res.success) {
				const {data: {records}} = res;
				commit('setAccountList', records)
				if (!records.length) {
					commit('setDefaultAccount', null);
				} else {
					const listTmp = records.filter(item => item.defaulted);
					if (listTmp.length) {
						commit('setDefaultAccount', listTmp[0]);
					} else if(records.length) {
						commit('setDefaultAccount', records[0]);
					}
				}
			}
		})
	}
}

const mutations = {
	setUserInfo(state, data) {
		state.userInfo = data;
	},
	removeUserInfo() {
		state.userInfo = null
	},
	setRecordList(state, data) {
		state.recordList = data;
	},
	setAddressList(state, data) {
		state.addressList = data;
	},
	setSelectAddress(state, data) {
		state.selectAddress = data;
	},
	setSelectAccount(state, data) {
		state.selectAccount = data;
	},
	setDefaultAddress (state, data) {
		state.defaultAddress = data;
	},
	setAccountList(state, data) {
		state.accountList = data;
	},
	setDefaultAccount(state, data) {
		state.defaultAccount = data;
	}
}
export default {
	namespaced: true,
	state,
	actions,
	mutations
}